<template>
  <div style="position: relative">
    <div
      v-if="isCalling && !isAutoAnswer"
      class="bj"
      @click="hangupCall"
      ref="dragElement"
    >
      <div class="bjsl">
        <img
          @mouseenter="thIndex = 1"
          v-if="thIndex === 0"
          src="@/assets/guangboimg/通话中.png"
          alt=""
        />
        <img
          @mouseleave="thIndex = 0"
          v-else
          src="@/assets/guangboimg/通话挂断.png"
          alt=""
        />
        <div class="num">{{ callDuration }}</div>
      </div>
    </div>
    <!-- 音频元素 -->
    <audio ref="remoteAudio" autoplay controls style="display: none"></audio>
    <div style="text-align: center; height: 100%; width: 100%">
      <!-- <audio ref="audioPlayer" controls></audio> -->
      <el-button
        @click="weijieFn"
        class="btm"
        round
        style="width: 100px; background-color: #ff6e6e; color: #fff"
      >
        <svg-icon class-name="icon" icon-class="bottom1" />
        <span style="margin-left: 5px">未接来电</span>
        <span class="num">{{ state.tableData.length }}</span></el-button
      >
      <el-button
        @click="hujiaoFn"
        round
        style="width: 100px; background-color: #28bf65; color: #fff"
      >
        <svg-icon class-name="icon" icon-class="bottom2" />
        <span style="margin-left: 5px">呼叫</span></el-button
      >
      <el-button
        @click="jinjiFn"
        round
        style="width: 100px; background-color: #ff9238; color: #fff"
      >
        <svg-icon class-name="icon" icon-class="bottom3" />
        <span style="margin-left: 5px">紧急广播</span></el-button
      >
      <el-button
        @click="boyinFn"
        round
        style="width: 100px; background-color: #409eff; color: #fff"
      >
        <svg-icon class-name="icon" icon-class="bottom4" />
        <span style="margin-left: 5px">播音</span></el-button
      >
    </div>
  </div>
  <!-- 未接来电 -->
  <el-dialog
    draggable
    v-model="state.weijieFlag"
    width="50%"
    :before-close="weijieClose"
  >
    <template #header>
      <span style="font-weight: 700">未接来电</span>
    </template>
    <div style="display: flex; align-items: center">
      <span>时间选择</span>
      <span>
        <el-date-picker
          style="margin: 0 20px 0 10px"
          :disabled-date="disabledDate"
          v-model="state.time"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </span>
      <el-button @click="searchFn" type="primary">查询</el-button>
      <el-button @click="resetFn">重置</el-button>
    </div>
    <div class="top">
      <div
        @click="jinriFn"
        :class="state.topIndex == 1 ? 'activeColor' : 'widthColor'"
      >
        今日
      </div>
      <div
        @click="zuoriFn"
        :class="state.topIndex == 2 ? 'activeColor' : 'widthColor'"
      >
        昨日
      </div>
      <div
        @click="benzhouFn"
        :class="state.topIndex == 3 ? 'activeColor' : 'widthColor'"
      >
        本周
      </div>
    </div>
    <el-table :data="state.tableData" height="280px">
      <el-table-column
        v-for="(item, index) in state.tableheads_show"
        :label="item.header"
        :prop="item.field"
        :key="index"
        :width="item.width ? item.width : ''"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span v-if="item.field == 'status'">
            {{ scope.row.status == 0 ? "未接" : "已接" }}
          </span>
          <span v-else-if="item.field == 'file'">
            {{ scope.row[item.field]?.fileName }}
          </span>
          <span v-else>
            {{ scope.row[item.field] }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template #default="scope">
          <!-- <el-button
            v-if="scope.row?.RecordFileList?.length != 0"
            @click="chakanluyinFn(scope)"
            type="text"
            >查看录音</el-button
          > -->
          <el-button type="text" @click="huibo(scope.row)"> 回拨 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px; display: flex; justify-content: flex-end">
      <el-pagination
        v-model:current-page="state.pageTotal.currentPage"
        v-model:page-size="state.pageTotal.pageSize"
        :page-sizes="[20, 30, 40, 50, 100]"
        :size="size"
        background
        layout="prev, pager, next, sizes, jumper, total"
        :total="state.pageTotal.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-dialog>
  <!-- 呼叫 -->
  <el-dialog
    draggable
    v-model="state.hujiaoFlag"
    width="30%"
    :before-close="hujiaoClose"
  >
    <template #header>
      <span style="font-weight: 700">呼叫</span>
    </template>
    <el-form
      ref="hujiaoRef"
      :model="state.hujiaoform"
      :rules="state.hujiaorules"
      label-width="auto"
    >
      <el-form-item label="主叫号码" prop="zhujiaoPhone">
        <el-input
          disabled
          maxlength="4"
          v-model="state.hujiaoform.zhujiaoPhone"
          placeholder="请输入主叫号码"
        ></el-input>
      </el-form-item>
      <el-form-item label="被叫广播号码" prop="hjshebei">
        <!-- v-show="!state.kongxianhujiaoFlag" -->
        <el-select
          style="width: 100%"
          @change="beijiaoChangeFn"
          v-model="state.hujiaoform.hjshebei"
          multiple
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) in state.telephoneData"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <div v-if="isCalling" style="text-align: center; margin-top: 20px;color: #28bf65;">
        <span>通话时长：{{ callDuration }}</span>
      </div> -->
      <!-- <div class="kongxianhujiaoVideo" v-show="state.kongxianhujiaoFlag">
        <div class="right">
          <div class="xiangqingVideo">
            <div
              style="width: 100%; height: 100%"
              v-if="
                state.detailShipinData.IsPreview !== false &&
                state.detailShipinData.dizengIP
              "
            >
              <iframe
                :id="`iframe-hujiao`"
                src="/iframe.html"
                frameborder="0"
                scrolling="no"
                style="width: 100%; height: 100%"
              >
              </iframe>
              {{ sendImageUrlToIframehujiao() }}
            </div>
            <div v-else class="wushipin">
              <img
                style="width: 100px; height: 100px"
                src="@/assets/guangboimg/监控摄像头.png"
                alt=""
              />
              <span style="letter-spacing: 5px">设备未连接</span>
            </div>
          </div>
        </div>
      </div> -->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <!-- v-if="!state.kongxianhujiaoFlag" -->
        <!-- <el-button @click="hujiaoClose">挂断</el-button> -->
        <el-button :disabled="jietingFlag" type="primary" @click="savehujiaoFn">
          {{ jietingFlag ? "呼叫中..." : "呼叫" }}
        </el-button>
      </div>
      <!-- <div v-else style="text-align: center">
        <img
          v-if="!state.hjgdFlag"
          @click="savehujiaoFn"
          style="width: 50px; height: 50px"
          src="@/assets/guangboimg/呼叫.png"
          alt=""
        />
        <img
          v-else
          @click="hujiaoClose"
          style="width: 50px; height: 50px"
          src="@/assets/guangboimg/挂断.png"
          alt=""
        />
      </div> -->
    </template>
  </el-dialog>
  <!-- 紧急广播 -->
  <el-dialog
    draggable
    v-model="state.jinjiFlag"
    width="20%"
    :before-close="jinjiClose"
  >
    <template #header>
      <span style="font-weight: 700">紧急广播</span>
    </template>
    <el-form
      ref="jinjiRef"
      :model="state.jinjigbform"
      :rules="state.jinjirules"
      label-width="auto"
    >
      <el-form-item label="广播设备" prop="shebei">
        <el-select
          v-model="state.jinjigbform.shebei"
          collapse-tags
          collapse-tags-tooltip
          style="width: 100%"
          multiple
          prop="shebei"
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) in state.telephoneData"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label=" ">
        <el-radio-group
          v-model="state.jinjigbform.radio1"
          @change="radioFn"
          class="ml-4"
        >
          <el-radio :label="1" size="large">文本</el-radio>
          <el-radio :label="2" size="large">语音</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="state.jinjigbform.radio1 == 1"
        label="广播内容"
        prop="neirong"
      >
        <el-input
          placeholder="请输入广播内容,最多30字"
          type="textarea"
          v-model="state.jinjigbform.neirong"
          maxlength="30"
        ></el-input>
      </el-form-item>
      <el-form-item v-show="state.jinjigbform.radio1 == 2" label=" ">
        <luyin
          ref="luyinRef"
          :shebei="state.jinjigbform.shebei"
          :num="state.jinjigbform.num"
          @refreshData="emit('refreshData')"
        ></luyin>
      </el-form-item>
      <el-form-item label="播放次数" prop="num">
        <div style="display: flex">
          <el-input-number
            :min="1"
            @change="numChangeFn"
            v-model="state.jinjigbform.num"
            style="width: 60%"
          ></el-input-number>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="jinjiClose">取消</el-button>
        <el-button type="primary" @click="savejinjiFn"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 播音 -->
  <el-dialog
    draggable
    v-model="state.boyinFlag"
    width="20%"
    :before-close="boyinCloseAll"
  >
    <template #header>
      <span style="font-weight: 700">播音</span>
    </template>
    <el-form
      ref="boyinRef"
      :model="state.boyinform"
      :rules="state.boyinrules"
      label-width="auto"
    >
      <el-form-item label="播音内容" prop="neirong">
        <el-select v-model="state.boyinform.neirong" multiple>
          <el-option
            :label="item.fileName"
            :value="item.uuid"
            v-for="(item, index) in state.yinpinData"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="播放次数" prop="boyinnum">
        <div style="display: flex">
          <el-input-number
            :min="1"
            @change="numChangeFn2"
            v-model="state.boyinform.boyinnum"
            style="width: 60%"
          ></el-input-number>
        </div>
      </el-form-item>
      <el-form-item label="广播设备" prop="phone">
        <el-select
          v-model="state.boyinform.phone"
          multiple
          collapse-tags
          collapse-tags-tooltip
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) in state.telephoneData"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveboyinFn"> 开启 </el-button>
        <!-- <el-button @click="boyinClose">关闭</el-button> -->
      </div>
    </template>
  </el-dialog>
  <!-- 来电---是否接听 -->
  <el-dialog
    draggable
    :show-close="false"
    v-model="laidianFlag"
    width="50%"
    :before-close="rejectCall"
    :close-on-click-modal="false"
  >
    <template #header>
      <span style="font-weight: 700">来电</span>
    </template>
    <div style="text-align: center; margin: 20px 0">
      <span
        >来电号码：<span
          style="font-weight: 700; font-size: 16px; color: #409eff"
          >{{ incomingCaller }}</span
        ></span
      >
    </div>
    <div
      v-if="isCalling"
      style="text-align: center; margin-top: 20px; color: #28bf65"
    >
      <span>通话时长：{{ callDuration }}</span>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button :disabled="jietingFlag" @click="rejectCall"
          >拒绝来电</el-button
        >
        <el-button :disabled="jietingFlag" type="primary" @click="answerCall">
          {{ jietingFlag ? "接听中..." : "接听来电" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import axios from "@/utils/request";
import luyin from "./luyin.vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import dayjs from "dayjs";
import { onBeforeUnmount, onMounted, onUnmounted, ref } from "vue";
import usepagesStore from "@/store/modules/pages";
const usepageStore = usepagesStore();
import * as SIP from "sip.js";
const { proxy } = getCurrentInstance();
const emit = defineEmits(["refreshData"]);
let state = reactive({
  //未接来电
  tableData: [],
  weijieFlag: false,
  topIndex: 1, //今日
  time: "", //时间
  jinzuoriTime: [], //今日,昨日,本周时间
  //呼叫
  hujiaoFlag: false,
  hujiaoform: {
    zhujiaoPhone: "1003",
    hjshebei: [],
  },
  hujiaorules: {
    //呼叫
    zhujiaoPhone: [
      {
        required: true,
        message: "请输入四位数字主叫号码",
        trigger: "change",
        /**正则校验判断是否是四位数字 */

        validator(rule, value, callback) {
          if (!/^\d{4}$/.test(value)) {
            callback(new Error("请输入正确的主叫号码"));
          } else {
            callback();
          } // 校验通过 callback()
          // 校验失败 callback(new Error('error message'))
        },
      },
    ],
    hjshebei: [
      {
        required: true,
        message: "请选择呼叫设备",
        trigger: "change",
      },
    ],
  },
  telephoneData: [], //广播设备
  kongxianhujiaoFlag: false, //空闲呼叫，用于区分底部呼叫
  hjgdFlag: false, //呼叫挂断
  detailShipinData: {}, //空闲通话详情
  //紧急广播
  jinjiFlag: false,
  jinjigbform: {
    shebei: [],
    neirong: "",
    radio1: 1,
    num: 1,
  },
  jinjirules: {
    shebei: [
      {
        required: true,
        message: "请选择广播设备",
        trigger: "change",
      },
    ],
    neirong: [
      {
        required: true,
        message: "请输入广播内容",
        trigger: "change",
      },
    ],
    num: [
      {
        required: true,
        message: "请输入播放次数",
        trigger: "change",
      },
    ],
  },
  //播音
  boyinFlag: false,
  boyinform: {
    neirong: [],
    boyinnum: 1,
    phone: [],
  },
  boyinrules: {
    neirong: [
      {
        required: true,
        message: "请选择播音内容",
        trigger: "change",
      },
    ],
    phone: [
      {
        required: true,
        message: "请选择广播设备",
        trigger: "change",
      },
    ],
    boyinnum: [
      {
        required: true,
        message: "请输入播放次数",
        trigger: "change",
      },
    ],
  },
  yinpinData: [], //所有音频列表
  pageTotal: {
    currentPage: 1,
    pageSize: 20,
    total: 0,
  },
  boyinUrl: "/callingCenter/broadcast",
});
const disabledDate = (time) => {
  return time.getTime() > Date.now() - 8.64e7 / 4; // 8.64e7 毫秒数代表一天
};
//未接来电
function weijieFn() {
  getHeader();
}
function weijieClose() {
  //未接来电关闭
  state.pageTotal.currentPage = 1;
  state.pageTotal.pageSize = 20;
  state.weijieFlag = false;
  state.topIndex = 1;
}
function searchFn() {
  //未接来电查询
  state.jinzuoriTime = [];
  // state.topIndex = 0;
  getList();
}
function resetFn() {
  //未接来电重置
  state.topIndex = 0;
  jinriFn();
  // timeFn();
}
function huibo(row) {
  //未接来电回拨
  console.log(row, "row");
}
//呼叫
function hujiaoFn() {
  state.hujiaoform.hjshebei = [];
  // state.hujiaoform.zhujiaoPhone = "";
  state.kongxianhujiaoFlag = false;
  state.hujiaoFlag = true;
}
function hujiaoClose() {
  //呼叫关闭
  // if (state.hjgdFlag == true) {
  // emit("guaduanFn", state.hujiaoform.hjshebei, "tonghuAall");
  hangupCall();
  state.hujiaoform.hjshebei = [];
  state.hujiaoFlag = false;
  proxy.$refs["hujiaoRef"].clearValidate();
  // ws.value.close(1000, "正常关闭");
  // setTimeout(() => {
  //   clearTimeout(state.sendTimer);
  //   state.recorder.destroy();
  // }, 500);
  // }
  // state.hujiaoFlag = false;
  // state.hjgdFlag = false;
}
function savehujiaoFn() {
  //呼叫保存
  console.log(state.hujiaoform.hjshebei, "state.hujiaoform.hjshebei");
  proxy.$refs["hujiaoRef"].validate((isOk) => {
    if (isOk) {
      //sip呼叫
      if (state.hujiaoform.hjshebei.length == 1) {
        targetNumber.value = state.hujiaoform.hjshebei[0];
        makeCall();
      } else if (state.hujiaoform.hjshebei.length > 1) {
        axios
          .post("/callingCenter/conference/open", {
            hostNumber: state.hujiaoform.zhujiaoPhone,
            guestNumbers: state.hujiaoform.hjshebei,
          })
          .then((res) => {
            if (res.code == 200) {
            }
          });
      }
    }
  });
}
//紧急广播
function numChangeFn(e) {
  //紧急广播播放次数
  if (e > 100) {
    ElMessage.warning("播放次数不能大于100次");
    state.jinjigbform.num = 100;
    return;
  } else {
    state.jinjigbform.num = e;
  }
}
function radioFn(e) {
  clearInterval(proxy.$refs["luyinRef"].timer);
  // console.log(e,'e');
  // console.log(state.form.radio1,'state.form.radio1');
}
function jinjiFn() {
  // state.jinjigbform.shebei = [];
  // state.jinjigbform.neirong = '';
  // state.jinjigbform.radio1 = 2;
  // state.jinjigbform.num = 1;
  state.jinjiFlag = true;
}
function jinjiClose() {
  //紧急广播关闭
  proxy.$refs["jinjiRef"].clearValidate();
  clearInterval(proxy.$refs["luyinRef"].timer);
  proxy.$refs["luyinRef"].data.showAnima = null;
  proxy.$refs["luyinRef"].data.duration = "00:00:01";
  state.jinjigbform.shebei = [];
  state.jinjigbform.neirong = "";
  state.jinjigbform.radio1 = 2;
  state.jinjigbform.num = 1;
  state.jinjiFlag = false;
}
function savejinjiFn() {
  //紧急广播保存
  proxy.$refs["jinjiRef"].validate((isOk) => {
    if (isOk) {
      if (state.jinjigbform.radio1 == 1) {
        //文本
        axios
          .post("/callingCenter/tts", { text: state.jinjigbform.neirong })
          .then((res) => {
            if (res.code == 200) {
              axios
                .post(state.boyinUrl, {
                  guestNumbers: state.jinjigbform.shebei,
                  fileUuid: [res.data],
                  loopType: 0, //0次数,1时长
                  loopCount: state.jinjigbform.num,
                })
                .then((res) => {
                  if (res.code == 200) {
                    emit("refreshData");
                    ElMessage.success(res.msg);
                    jinjiClose();
                  } else {
                    ElMessage.error(res.msg);
                  }
                });
            } else {
              ElMessage.error(res.msg);
            }
          });
      } else if (state.jinjigbform.radio1 == 2) {
        if (proxy.$refs["luyinRef"].data.recorder == null) {
          ElMessage.warning("请先录音");
          return;
        } else {
          proxy.$refs["luyinRef"].submit();
        }
      }
      proxy.$refs["jinjiRef"].clearValidate();
      state.jinjiFlag = false;
      // state.jinjigbform.shebei=[]
      // state.jinjigbform.neirong=[]
      // state.jinjigbform.radio1=2
      // state.jinjigbform.num=1
    }
  });
}
//播音
function numChangeFn2(e) {
  //播音播放次数
  if (e > 100) {
    ElMessage.warning("播放次数不能大于100次");
    state.boyinform.boyinnum = 100;
    return;
  } else {
    state.boyinform.boyinnum = e;
  }
}
function boyinFn() {
  //播音
  // state.boyinform.neirong=[]
  // state.boyinform.boyinnum=1
  // state.boyinform.phone=[]
  state.boyinFlag = true;
}
function boyinCloseAll() {
  proxy.$refs["boyinRef"].clearValidate();
  state.boyinform.neirong = [];
  state.boyinform.boyinnum = 1;
  state.boyinform.phone = [];
  state.boyinFlag = false;
}
function boyinClose() {
  //播音关闭
  if (state.endData) {
    proxy.$refs["boyinRef"].validate((isOk) => {
      if (isOk) {
        axios
          .post(`/callingCenter/conference/close/${state.endData}`, {})
          .then((res) => {
            ElMessage.success("关闭成功");
            state.boyinFlag = false;
            state.boyinform.neirong = [];
            state.boyinform.boyinnum = 1;
            state.boyinform.phone = [];
          });
      }
    });
  } else {
    ElMessage.error(res.msg);
  }
}
function saveboyinFn() {
  //播音保存
  console.log(state.boyinform, "state.boyinform");
  //开启
  proxy.$refs["boyinRef"].validate((isOk) => {
    if (isOk) {
      // const remainingPath = state.detailData.url.replace(
      //   /^https?:\/\/[^\/]+/,
      //   ""
      // );
      axios
        .post(state.boyinUrl, {
          guestNumbers: state.boyinform.phone,
          fileUuid: state.boyinform.neirong,
          loopType: 0, //0次数,1时长
          loopCount: state.boyinform.boyinnum,
        })
        .then((res) => {
          if (res.code == 200) {
            ElMessage.success(res.msg);
            proxy.$refs["boyinRef"].clearValidate();
            state.endData = res.data;
            state.boyinFlag = false; //返回data数据用以关闭
            state.boyinform.neirong = [];
            state.boyinform.boyinnum = 1;
            state.boyinform.phone = [];
            emit("refreshData");
          } else {
            ElMessage.error(res.msg);
          }
        });
    }
  });
}
//今日
function jinriFn() {
  state.topIndex = 1;
  let date = getTodayDate();
  state.jinzuoriTime = [date + "00:00:00", date + "23:59:59"];
  state.time = [date + "00:00:00", date + "23:59:59"];
  getList();
}
//昨日
function zuoriFn() {
  state.topIndex = 2;
  let date = getYesterdayDate();
  state.jinzuoriTime = [date + " " + "00:00:00", date + " " + "23:59:59"];
  state.time = [date + " " + "00:00:00", date + " " + "23:59:59"];
  getList();
}
//本周
function benzhouFn() {
  state.topIndex = 3;
  const { start, end } = getThisWeekDates();
  let date = start.year + "-" + start.month + "-" + start.day + " ";
  let date2 = end.year + "-" + end.month + "-" + end.day + " ";
  state.jinzuoriTime = [date + " " + "00:00:00", date2 + " " + "23:59:59"];
  state.time = [date + " " + "00:00:00", date2 + " " + "23:59:59"];
  getList();
}
//今日日期
function getTodayDate() {
  const now = new Date();
  const year = now.getFullYear(); // 获取当前年份
  let month = now.getMonth() + 1; // 获取当前月份，注意getMonth()返回的是0-11，所以需要加1
  let day = now.getDate(); // 获取当前日期
  month = month < 10 ? "0" + month : month;
  day = day < 10 ? "0" + day : day;
  const date = year + "-" + month + "-" + day + " ";
  return date;
}
//昨日日期
function getYesterdayDate() {
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);
  const year = yesterday.getFullYear();
  const month = ("0" + (yesterday.getMonth() + 1)).slice(-2); // 月份是从0开始的
  const day = ("0" + yesterday.getDate()).slice(-2);
  return `${year}-${month}-${day}`;
}
//本周日期
function getThisWeekDates() {
  const now = new Date();
  const dayOfWeek = now.getDay();
  const dayOffset = dayOfWeek - 1;

  const startDate = new Date(now - dayOffset * 86400000); // 当前日期减去本周第一天的偏移量
  const endDate = new Date(startDate.getTime() + 6 * 86400000); // 开始日期加上6天的毫秒数

  const startYear = startDate.getFullYear();
  let startMonth = startDate.getMonth() + 1; // 月份是从0开始的
  let startDay = startDate.getDate();
  startMonth = startMonth < 10 ? "0" + startMonth : startMonth;
  startDay = startDay < 10 ? "0" + startDay : startDay;
  const endYear = endDate.getFullYear();
  let endMonth = endDate.getMonth() + 1;
  let endDay = endDate.getDate();
  endMonth = endMonth < 10 ? "0" + endMonth : endMonth;
  endDay = endDay < 10 ? "0" + endDay : endDay;
  return {
    start: { year: startYear, month: startMonth, day: startDay },
    end: { year: endYear, month: endMonth, day: endDay },
  };
}
const getHeader = () => {
  //获取头部数据
  let table_headers = reactive({});
  axios.get("/vxeheaders/getHeaders").then((res) => {
    let set = new Set();
    res.data.forEach((item) => {
      set.add(item.name);
    });
    set.forEach((item) => {
      let arr = [];
      res.data.forEach((item2) => {
        if (item2.name === item) {
          arr.push(item2);
        }
      });
      table_headers[item] = arr;
    });
    state.tableheads_show = computed(() => {
      return table_headers.t_sip_contact_record.filter(
        (item) => item.show === 1
      );
    });
    state.weijieFlag = true;
    //show为1的返回表头
    jinriFn();
  });
};
//分页
function handleSizeChange(val) {
  // console.log(val, "当前页");
  state.pageTotal.pageSize = val;
  getList();
}
function handleCurrentChange(val) {
  // console.log(val, "当前页");
  state.pageTotal.currentPage = val;
  getList();
}
function getList() {
  axios
    .post("/sip/contactRecord/list", {
      queryStartTime: state.jinzuoriTime[0],
      queryEndTime: state.jinzuoriTime[1],
      pageNum: state.pageTotal.currentPage,
      pageSize: state.pageTotal.pageSize,
      status: 0, //是否接通，1接通，0未接通 ''全部
      // callerNumber:state.jiluDetail.zhujiaoTerminalNO,//主叫号码
      calleeNumber: "1000", //被叫号码,每个登录账号绑定一个号码
    })
    .then((res) => {
      if (res.data?.list) {
        state.tableData = res.data.list;
        state.pageTotal.total = res.data.total;
      }
    });
}
function getPhoneList(id) {
  //广播设备号码
  state.telephoneData = [];
  let arr = [];
  axios
    .post("/sip/config/user/listNoPage", {
      groupId: id == 0 ? "" : id,
    })
    .then((res) => {
      if (res.data?.length > 0) {
        arr = [];
        res.data.forEach((val) => {
          //搜索播放终端
          // if(val.userNumber!=state.hujiaoform.zhujiaoPhone){
          // arr.push({ label: val.userNumber, value: val.userNumber });
          // }
          arr.push({ label: val.userNumber, value: val.userNumber });
        });
        state.telephoneData = arr;
      }
    });
}
function getAllYinpinList() {
  let arr = [];
  axios.post("/sip/config/file/list", {}).then((res) => {
    res.data.list.forEach((item) => {
      if (item.type == 0) {
        arr.push(item);
      }
    });
    state.yinpinData = arr;
  });
}
function shipinChakan(TerminalNO) {
  //详情查看视频
  // axios
  //   .post("/Service/GetWebApiCameraList", {
  //     //获取摄像头信息
  //     CameraID: -1,
  //     TerminalNO: TerminalNO, //string
  //     CameraIP: "",
  //     Place: "",
  //     // CameraID: node.CameraID, //0,获取所有
  //   })
  //   .then((res) => {
  //     if (res.DataList?.length > 0) {
  //       state.shipinData = res.DataList;
  //       getCameraList(res.DataList);
  //     }
  //   });
}
//sip对讲
// 获取本机IP
let localIP = ref("");
let incomingCaller = ref(""); //来电号码
let currentSession = ref(null); //当前通话会话
let currentInvitation = ref(null); //当前通话邀请
let callDuration = ref("00:00"); //通话时长
let remoteAudio = ref(null);
let userAgent = ref(null);
let registerer = ref(null);
let targetNumber = ref("1004"); //目标号码
let callStartTime = ref(null);
let isCalling = ref(false); //是否正在通话
let laidianFlag = ref(false); //来电
let jietingFlag = ref(false); //接听中...
let thIndex = ref(0);
let isAutoAnswer = ref(false); //是否自动接听
// 服务器配置
const server = ref("wss://172.16.49.121:7443");
const username = ref("1003");
const password = ref("112233");
const domain = ref("172.16.49.121");
const getLocalIP = () => {
  return new Promise((resolve, reject) => {
    window.RTCPeerConnection =
      window.RTCPeerConnection ||
      window.mozRTCPeerConnection ||
      window.webkitRTCPeerConnection;

    if (!window.RTCPeerConnection) {
      reject("您的浏览器不支持WebRTC API");
      return;
    }

    const pc = new RTCPeerConnection({ iceServers: [] });
    pc.createDataChannel("");
    pc.createOffer().then((offer) => pc.setLocalDescription(offer));

    pc.onicecandidate = (event) => {
      if (event.candidate) {
        const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
        const ipMatch = event.candidate.candidate.match(ipRegex);
        if (ipMatch) {
          resolve(ipMatch[1]);
          pc.onicecandidate = null;
        }
      }
    };

    setTimeout(() => {
      resolve("127.0.0.1");
    }, 1000);
  });
};
// 连接服务器
const connect = async () => {
  try {
    // 创建正确的URI
    const uri = SIP.UserAgent.makeURI(`sip:${username.value}@${domain.value}`);
    if (!uri) {
      throw new Error("无效的SIP URI");
    }
    // 创建UserAgent，强制使用正确的Contact头
    userAgent.value = new SIP.UserAgent({
      uri,
      viaHost: localIP.value,
      transportOptions: {
        server: server.value,
      },
      authorizationUsername: username.value,
      authorizationPassword: password.value,
      sessionDescriptionHandlerOptions: {
        constraints: {
          audio: true,
          video: false,
        },
      },
      // 强制使用正确的Contact参数
      contactName: username.value,
      contactParams: {
        transport: "ws",
        host: localIP.value,
        port: "7443",
      },
      // 委托配置
      delegate: {
        onInvite: (invitation) => {
          console.log("收到来电", invitation);
          incomingCaller.value =
            invitation.remoteIdentity.uri.user || "未知号码";
          currentInvitation.value = invitation;
          // answerCall();
          // 获取原始INVITE消息 - 关键代码
          if (invitation && invitation.request) {
            const rawMessage = invitation.request.toString();
            console.log("原始INVITE内容999:", rawMessage);
            if (rawMessage.includes("answer-after=0")) {
              //自动接听
              isAutoAnswer.value = true;
              // console.log("原始INVITE内容999:", rawMessage);
              answerCall();
            } else {
              isAutoAnswer.value = false;
              laidianFlag.value = true;
            }
          } else {
            console.error("无法获取原始消息 - invitation.request 不存在");
          }
          // 监听邀请状态变化
          invitation.stateChange.addListener((state) => {
            if (state === SIP.SessionState.Established) {
              // 通话建立后设置音频
              setTimeout(() => {
                setupRemoteAudio(invitation);
              }, 500);
            } else if (state === SIP.SessionState.Terminated) {
              // 通话被对方挂断
              handleCallEnded("对方已挂断通话");
            }
          });
        },
      },
    });
    // 创建注册器
    registerer.value = new SIP.Registerer(userAgent.value);
    // 监听注册状态
    registerer.value.stateChange.addListener((state) => {
      if (state === SIP.RegistererState.Registered) {
        // addLog("SIP注册成功", "success");
      } else if (state === SIP.RegistererState.Unregistered) {
        // addLog("SIP已注销", "info");
      }
    });
    // 重写注册器的register方法，强制使用正确的Contact头
    const originalRegister = registerer.value.register.bind(registerer.value);
    registerer.value.register = async (options = {}) => {
      options.extraHeaders = options.extraHeaders || [];
      options.extraHeaders.push(
        `Contact: <sip:${username.value}@${domain.value};transport=ws>`
      );
      return originalRegister(options);
    };
    // 启动UserAgent
    await userAgent.value.start();
    // 现在transport已经创建，我们可以重写onMessage了
    // const originalOnMessage = userAgent.value.transport.onMessage;
    // userAgent.value.transport.onMessage = (message) => {
    //   // 先执行我们自己的日志打印
    //   if (message && message.includes("INVITE")) {
    //     console.log("=== 接收到INVITE消息 ===");
    //     console.log("原始INVITE内容999:", message);
    // };
    // addLog("SIP服务器连接成功", "success");
    // 注册SIP
    await registerSip();
  } catch (error) {
    // addLog(`连接失败: ${error.message}`, "error");
    console.error("连接错误详情:", error);
  }
};
// 注册SIP
const registerSip = async () => {
  try {
    if (!userAgent.value || !registerer.value) {
      // addLog("SIP客户端未初始化", "error");
      return;
    }
    // addLog("正在注册SIP账号...", "info");
    const options = {
      extraHeaders: [
        `Contact: <sip:${username.value}@${domain.value};transport=ws>`,
      ],
    };
    await registerer.value.register(options);
    setTimeout(() => {
      emit("refreshData");
    }, 500);
  } catch (error) {
    // addLog(`SIP注册失败: ${error.message}`, "error");
    console.error("注册错误详情:", error);
  }
};
// 发起呼叫
const makeCall = async () => {
  if (!targetNumber.value) {
    // addLog("请输入目标号码", "warning");
    return;
  }
  try {
    if (!userAgent.value) {
      // addLog("SIP客户端未初始化", "error");
      return;
    }
    // addLog(`正在呼叫 ${targetNumber.value}...`, "info");
    const targetUri = SIP.UserAgent.makeURI(
      `sip:${targetNumber.value}@${domain.value}`
    );
    if (!targetUri) {
      throw new Error("无效的目标SIP URI");
    }
    jietingFlag.value = true;
    // 创建邀请
    const inviter = new SIP.Inviter(userAgent.value, targetUri, {
      sessionDescriptionHandlerOptions: {
        constraints: {
          audio: true,
          video: false,
        },
      },
    });

    // 监听邀请状态
    inviter.stateChange.addListener((state) => {
      // addLog(`邀请状态: ${state}`, "info");
      if (state === SIP.SessionState.Established) {
        startCallTimer();
        // addLog("通话已接通", "success");
        // 通话建立后设置音频，添加延迟确保一切就绪
        setTimeout(() => {
          setupRemoteAudio(inviter);
        }, 500);
      } else if (state === SIP.SessionState.Terminated) {
        // 通话被对方挂断或异常结束
        handleCallEnded("通话已结束");
      }
    });
    // 发送邀请
    await inviter.invite();
    currentSession.value = inviter;
  } catch (error) {
    // addLog(`呼叫失败: ${error.message}`, "error");
  }
};
// 接听来电
const answerCall = async () => {
  try {
    if (!currentInvitation.value) {
      // addLog("没有待接听的来电", "error");
      return;
    }
    jietingFlag.value = true;
    // addLog("正在接听来电...", "info");
    const options = {
      sessionDescriptionHandlerOptions: {
        constraints: {
          audio: true,
          video: false,
        },
      },
    };
    await currentInvitation.value.accept(options);
    startCallTimer();
    // addLog("来电已接听", "success");
    currentSession.value = currentInvitation.value;
    currentInvitation.value = null;
  } catch (error) {}
};
// 拒绝来电
const rejectCall = async () => {
  try {
    if (currentInvitation.value) {
      await currentInvitation.value.reject();
      laidianFlag.value = false;
      // addLog("来电已拒绝", "info");
    }
  } catch (error) {
    // addLog(`拒绝来电失败: ${error.message}`, "error");
  } finally {
    currentInvitation.value = null;
  }
};
// 挂断通话
const hangupCall = async (item) => {
  try {
    if (currentSession.value) {
      laidianFlag.value = false;
      await currentSession.value.bye();
      // addLog("通话已挂断", "info");
    }
  } catch (error) {
    // addLog(`挂断失败: ${error.message}`, "error");
  } finally {
    handleCallEnded("通话已挂断");
  }
};
// 注销SIP
const unregister = async () => {
  try {
    if (registerer.value) {
      await registerer.value.unregister();
      // addLog("SIP注销成功", "success");
    }
  } catch (error) {
    // addLog(`注销失败: ${error.message}`, "error");
  }
};
// 设置远程音频流 - 改进版本
const setupRemoteAudio = (session) => {
  // 确保DOM已更新
  nextTick(() => {
    if (!session) {
      // addLog("会话未就绪", "warning");
      return;
    }
    if (!remoteAudio.value) {
      // addLog("音频元素未就绪，等待重试...", "warning");
      // 重试机制
      setTimeout(() => {
        setupRemoteAudio(session);
      }, 300);
      return;
    }

    try {
      // 获取会话描述处理器
      const sessionDescriptionHandler = session.sessionDescriptionHandler;

      if (!sessionDescriptionHandler) {
        // addLog("会话描述处理器未找到，等待重试...", "warning");
        setTimeout(() => {
          setupRemoteAudio(session);
        }, 300);
        return;
      }

      // 获取对等连接
      const peerConnection = sessionDescriptionHandler.peerConnection;

      if (!peerConnection) {
        // addLog("对等连接未建立，等待重试...", "warning");
        setTimeout(() => {
          setupRemoteAudio(session);
        }, 300);
        return;
      }

      // // 方法1: 监听远程流事件
      // peerConnection.ontrack = (event) => {
      //   if (event.streams && event.streams[0]) {
      //     const remoteStream = event.streams[0];
      //     remoteAudio.value.srcObject = remoteStream;

      //     remoteAudio.value.play().catch((e) => {
      //       // addLog(`播放音频失败: ${e.message}`, "error");
      //     });

      //     // addLog("通过ontrack事件接收到远程音频流", "success");
      //   }
      // };

      // 方法2: 检查现有的接收器
      const receivers = peerConnection.getReceivers();
      const remoteTracks = receivers
        .filter((receiver) => receiver.track && receiver.track.kind === "audio")
        .map((receiver) => receiver.track);

      if (remoteTracks.length > 0) {
        const combinedStream = new MediaStream(remoteTracks);
        remoteAudio.value.srcObject = combinedStream;

        remoteAudio.value.play().catch((e) => {
          // addLog(`播放音频失败: ${e.message}`, "error");
        });

        // addLog("通过现有接收器获取到远程音频流", "success");
        return;
      }

      // // 方法3: 尝试从会话描述处理器获取远程流
      // try {
      //   const remoteMediaStream =
      //     sessionDescriptionHandler.getRemoteMediaStream();
      //   if (remoteMediaStream) {
      //     remoteAudio.value.srcObject = remoteMediaStream;

      //     remoteAudio.value.play().catch((e) => {
      //       // addLog(`播放音频失败: ${e.message}`, "error");
      //     });

      //     // addLog("通过getRemoteMediaStream获取到远程音频流", "success");
      //     return;
      //   }
      // } catch (error) {
      //   // 忽略此错误，继续尝试其他方法
      // }

      // 如果以上方法都失败，设置重试
      // addLog("未找到远程音频流，将在500ms后重试", "warning");
      setTimeout(() => {
        setupRemoteAudio(session);
      }, 500);
    } catch (error) {
      // addLog(`设置远程音频失败: ${error.message}`, "error");
      console.error("音频设置错误详情:", error);

      // 错误时也重试
      setTimeout(() => {
        setupRemoteAudio(session);
      }, 500);
    }
  });
};
// 处理通话结束 - 新增函数
const handleCallEnded = (reason = "通话已结束") => {
  // addLog(reason, "info");
  // isInCall.value = false;
  // incomingCall.value = false;
  stopCallTimer();
  cleanupAudio();
  // 清理当前会话
  currentSession.value = null;
  currentInvitation.value = null;
  // // 3秒后重置状态
  // setTimeout(() => {
  //   callStatus.value = "idle";
  // }, 3000);
};
// 清理音频
const cleanupAudio = () => {
  if (remoteAudio.value) {
    remoteAudio.value.srcObject = null;
    remoteAudio.value.pause();
  }
};
// 通话计时器
let callTimer = null;
const startCallTimer = () => {
  callStartTime.value = new Date();
  callTimer = setInterval(() => {
    const now = new Date();
    const duration = Math.floor((now - callStartTime.value) / 1000);
    const minutes = Math.floor(duration / 60)
      .toString()
      .padStart(2, "0");
    const seconds = (duration % 60).toString().padStart(2, "0");
    callDuration.value = `${minutes}:${seconds}`;
    isCalling.value = true;
    jietingFlag.value = false;
    laidianFlag.value = false;
    state.hujiaoFlag = false;
    thIndex.value = 0;
  }, 1000);
  setTimeout(() => {
    emit("refreshData");
  }, 1000);
};
const stopCallTimer = () => {
  if (callTimer) {
    clearInterval(callTimer);
    callTimer = null;
  }
  isCalling.value = false;
  callDuration.value = "00:00";
  setTimeout(() => {
    // ElMessage.warning("通话已结束");
    state.hujiaoFlag = false;
    jietingFlag.value = false;
    laidianFlag.value = false;
    emit("refreshData");
    // registerSip()
  }, 1000);
};
// 断开连接
const disconnect = async () => {
  if (currentSession.value) {
    await currentSession.value.bye();
  }

  if (registerer.value) {
    await registerer.value.unregister();
  }

  if (userAgent.value) {
    await userAgent.value.stop();
  }
  // isInCall.value = false;
  // incomingCall.value = false;
  stopCallTimer();
  cleanupAudio();
  // addLog("已断开所有连接", "info");
};

defineExpose({
  state,
  // ws,
  // getTonghuaingList,
  shipinChakan,
  hangupCall,
  // connectWebSocket,
});
onMounted(async () => {
  try {
    localIP.value = await getLocalIP();
  } catch (error) {
    localIP.value = "127.0.0.1";
  }
  nextTick(() => {
    connect();
  });
  getPhoneList(0); //广播设备
  getAllYinpinList(); //所有音频列表
});
onBeforeUnmount(() => {
  // disconnect();
});
</script>

<style scoped lang="scss">
.btm {
  position: relative;

  .num {
    position: absolute;
    font-size: 12px;
    top: -12px;
    right: 0;
    width: 20px;
    height: 20px;
    line-height: 20px;
    border-radius: 10px;
    background-color: red;
  }
}
//未接来电
.top {
  display: flex;
  margin: 10px 0;
  .widthColor {
    width: 60px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    background-color: #f2f3f5;
  }

  .activeColor {
    width: 60px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    background-color: #409eff;
    color: #fff;
  }
}
//空闲呼叫视频
.kongxianhujiaoVideo {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  .video-item {
    width: 49%;
    height: 150px;
    border-radius: 8px;
    margin-bottom: 8px;
    background-color: #cbcbcb;
  }
  .right {
    width: 100%;
    .xiangqingVideo {
      width: 100%;
      height: 300px;
      border-radius: 8px;
      background-color: #cbcbcb;
      .wushipin {
        width: 100%;
        height: 300px;
        border-radius: 8px;
        background-color: #f5f5f5;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 16px;
      }
    }
  }
}
</style>
<style scoped lang="scss">
.bj {
  right: 5px;
  bottom: -10px;
  z-index: 999;
  width: 52px;
  height: 52px;
  position: absolute;
  background-size: 110% 110%;
  cursor: pointer;
  color: #fff;
  font-weight: 700;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: center;
  img {
    width: 100%;
    height: 100%;
  }
  .bjsl {
    width: 100%;
    height: 100%;
    position: relative;
    .num {
      position: absolute;
      bottom: 5px;
      left: 10px;
      width: 50px;
      font-size: 12px;
    }
  }
}
</style>